package com.msunsoft.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.msunsoft.common.BaseService;
import com.msunsoft.exception.BusinessException;
import com.msunsoft.support.dozer.DozerMapperHelper;
import com.msunsoft.system.mybatis.dao.SysAreaMapper;
import com.msunsoft.system.mybatis.model.SysArea;
import com.msunsoft.system.vo.AreaTreeVo;


@Service
public class AreaService extends BaseService<SysAreaMapper, SysArea> {

    public List<AreaTreeVo> selectTreeByType(Integer areaType) {

        List<SysArea> list = this.dao.selectAllByType(areaType);
        List<AreaTreeVo> voList = new ArrayList();

        for (SysArea office : list) {
            AreaTreeVo vo = DozerMapperHelper.map(office, AreaTreeVo.class);
            vo.setText(vo.getName());

            voList.add(vo);
        }

        return genTree(voList);
    }

    public int deleteById4Tree(Integer id) {
        Integer count = this.dao.selectCountChildById(id);
        if (count != 0) {
            throw new BusinessException("非法操作!该节点下存在子节点,请先删除子节点!");
        }
        return super.deleteById (id);
    }
    
    /**
     * 给出查询到的数据,生成树形结构, (为easyui提供树形结构)
     * @param list 查询到的数据
     * @return 树形结构
     */
    //TODO 树形结构算法
    public List<AreaTreeVo> genTree(List<AreaTreeVo> list) {

//        List<MenuTreeVo> nodeList = new ArrayList<MenuTreeVo>();
//        for (MenuTreeVo node1 : list) {
//            boolean mark = false;
//            for (MenuTreeVo node2 : list) {
//                if ((node1.getParentId() != null) && node1.getParentId().equals(node2.getId())) {
//                    mark = true;
//                    if (node2.getChildren() == null) {
//                        node2.setChildren(new ArrayList<SysMenu>());
//                    }
//                    node2.getChildren().add(node1);
//                    break;
//                }
//            }
//            if (!mark) {
//                nodeList.add(node1);
//            }
//        }
        return list;
    }
}
